package com.bluexmicro.android.ota

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanResult
import android.content.Context
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import kotlin.jvm.Throws

object OtaParamHelper {

    // 1.根据MAC地址，获取Bluetooth
    @Throws(IllegalArgumentException::class)
    fun getBluetoothDevice(context: Context, mac: String): BluetoothDevice {
        val bluetoothMgr = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager?
            ?: throw IllegalArgumentException("Not support Bluetooth")
        val bleAdapter = bluetoothMgr.adapter ?: throw IllegalArgumentException("Bluetooth disable")
        if (BluetoothAdapter.checkBluetoothAddress(mac)) {
            return bleAdapter.getRemoteDevice(mac)
        } else {
            throw IllegalArgumentException("mac address invalid or please scan device first")
        }
    }

    // 2.根据扫描结果获取BluetoothDevice
    fun getBluetoothDevice(scanResult: ScanResult): BluetoothDevice {
        return scanResult.device
    }

    fun loadBinData(file: File): ByteArray? {
        var bytes: ByteArray? = null
        try {
            val fileInputStream = FileInputStream(file)
            bytes = ByteArray(fileInputStream.available())
            val size = fileInputStream.read(bytes)
            fileInputStream.close()
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return bytes
    }
}